package cn.tedu.plus.datetime;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SimpleDateFormatDemo {
    public static void main(String[] args) throws ParseException {
        //Date对象，现在时间
        Date now = new Date();
        System.out.println("Date现在时间:   " + now);

        //创建模式字符串
        String pattern1 = "yyyy-MM-dd HH:mm:ss";
        String pattern2 = "yyyy年MM月dd日 HH时mm分ss秒";
        String pattern3 = "HH:mm:ss:S";
        //创建SimpleDateFormat对象
        SimpleDateFormat sdf1 = new SimpleDateFormat(pattern1);
        SimpleDateFormat sdf2 = new SimpleDateFormat(pattern2);
        SimpleDateFormat sdf3 = new SimpleDateFormat(pattern3);
        //调用format方法
        String result1 = sdf1.format(now);
        String result2 = sdf2.format(now);
        String result3 = sdf3.format(now);

        System.out.println(pattern1 + "格式:  " + result1);
        System.out.println(pattern2 + "格式:  " + result2);
        System.out.println(pattern3 + "格式:  " + result3);


        String newPattern = "yyyy年MM月";
        //应用新模式，无需创新对象
        sdf1.applyPattern(newPattern);
        result1 = sdf1.format(now);
        System.out.println(newPattern + "格式  :" + result1);

        //将字符串转换为Date对象
        //字符串必须完全匹配，不然抛parse异常
        String dateString = "2024-10-8 10:48:56";
        String pattern4 = "yyyy-MM-dd HH:mm:ss";
        sdf1.applyPattern(pattern4);
        Date date = sdf1.parse(dateString);
        System.out.println(dateString + "转换为:  " + date);
    }
}
